package Work2;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    public static void main(String[] args) {
        try {

            ExecutorService pool = Executors.newFixedThreadPool(2);
            ServerSocket ser = new ServerSocket(6588);
            System.out.println("服务器等待链接..");
            Socket socket = ser.accept();
            System.out.println("客户端连接成功..");
            pool.execute(new chatIn(socket));
            pool.execute(new chatOut(socket));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    static class chatIn implements Runnable {
        private Socket socket;

        public chatIn(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {

            /**
             *
             */
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                while (true) {

                    String s = br.readLine();
                    System.out.println("客户端说:" + s);
                    if (s == null) {
                        break;
                    }
                }
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    static class chatOut implements Runnable {
        private Socket socket;

        public chatOut(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try (PrintWriter p = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
            ) {
                while (true) {
                    String input = InputUtils.Input("请输入想发送的信息:");
                    p.println(input);
                }


            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
